package com.tbit.uqbike.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.ExtendParams;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.tbit.common.exceptions.ExternalException;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.dao.core.MachineBorrowDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.UserOtherBound;
import com.tbit.uqbike.client.remote.zfb.ZMXYClient;
import com.tbit.uqbike.client.remote.zfb.util.OrderInfoUtil2_0;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.LogUtil;
import com.tbit.uqbike.client.util.OrderNoUtil;
import com.tbit.uqbike.client.util.TenpayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Service("zhifubaoPayService")
@Slf4j
public class ZhifubaoPayServiceImpl implements ZhifubaoPayService {
    @Autowired
    private UserService userService;
    @Autowired
    private ZfbPayConfigService zfbPayConfigService;
    @Autowired
    private AdAccountDepositService adAccountDepositService;
    @Autowired
    private AliConfigService aliConfigService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private AdaPayService adaPayService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private UserOtherBoundService userOtherBoundService;
    @Autowired
    private UserRewardLogService userRewardLogService;
    @Autowired
    private MachineBorrowDao machineBorrowDao;
    @Autowired
    private RedisService redisService;
    public static void main(String[] args) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do"
                , "2021004108659776"
                , "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCHpL/HlOfcpLd93aq6hre0nNQxIVNp9ETFpEAd+rUYIf0aPhb3lOa2wAdDzDIWruuCj/xRlhnrXBkoDVNRKVFZzkrUGN/W9F68zWpidp7o8qbiX4YdYCtV3Pzff04qSTucRLneqWxT/59RlrM6mNAwsPj3vQGTIj8CW2yS5Dn4KPw+EYkKbD3Hmf2lka1G/CNi/3Sje71b2+SwS7bmJjUUsRzd1TOlTK3m8wv4Imxt/cQ6sbbjcalrFkDTOn/ZyanhbkSpRBCdRs1+WxV4awZrm7pc6MohsXFMFzvBb3QH9ZDxWlOsQPa1lKnmgyKoVIgxwuRo5EdVuEhVrJi0ifSlAgMBAAECggEAWViLekr67rsQojeAXZyfJLiojDQHXaMoKYcnNJgO8PZyYPbE6g+KaJXUMzQtSgOt3TI6YQMdz4m6iEc+uhcdHqpjX5GC33PXc0Va7cB0q7wpcLK7BF50LPqDFjQkqHXUbfpW8/NlB2844eUB6Xb+qxPm6kf04ZWNK2BNA/SQuoROeAq+jEBnoCM+DIjhJbpb2+t4aUXogkLNOwGU+fZRLvF1DijfyPUuRwN3LlsZTqPT9v18lyh91cLTnbcGIBcv1guSNce8gJwRxouuZ7l5RMrB8D2ViX0wu6aSd4hCRE7HnIoQugDKZ67OayQ+QSkNaTe9w4tkGjS1Sh32ZeHcAQKBgQDIsRNbDOzKQuK6tFaQseDMbZk5taNXQckVaLyb94mt+/JFVQSOFkl6v4FJEo5mvEq18QgWuyPapgaJQ3vA/GEdP8nSaAiS/M5vKxMeBZhWu25DrZT3rW1TRHMQ6yC5iZNvp/B2oQi/xRlKW/gZ1SOr/9HOGwFzLuWU171X4m4m3QKBgQCtBnxuwVjPXS3g7WT4P+03UxozmETXiTY0cKa7UHdERC/r15T55o/fG8NfipHjquJ7oEi6CJUJa0vRjosa9MQdKGgM6NXa8bxjDdcebRVKK+JGUrjvcnJ0m4YZlEx87wF3YBTEihJsmBbajFSDw5YcazjHY0aaPRGc6o8JYpHUaQKBgBV0SJttMEsXB2HqMW7adSulc8HllwaW88YkIjWSKte8nVOoGQqPe19x5YJIR4zYCCyXDcRQUS7onL5DxpEE6eTUkuC5WmFMQU1FD5AgDP8InmsBvXEUyyEhqiNe32q2OFqxW1VzNZo6mc+HMWihjmSuvmEIJgmIM+bLgWRJwnjJAoGAA7AwtNewQfNViAbncRdDwjsmQtVLGmEVY7bHBxUnBbCCaP+WcGFGzdW0q3OzumupGkOHaVfHfYTo/9WPB4sSJyD2XtgTvvAKOP5RiJeAra0TzLX0tT32TKAIEsGDg+JAYMAOkUX0MJZpXk1Be/GOYJq0giOOnLkSiArD88pDG4kCgYB+XEPkClUDxaBw+xRK1+ZSmr4tnwFdy3PXlSTHpDlf3hCCB10tnEisYp/1rU2+kYCTTEIbLB60N7PT01hFmPR57KoUCb+ZIBOwAV4YPFvKfYY8EAlOHwvBfZfTyXSPuqmdmEuFVNklfXS61/ufhJcx0miZuQttzfU8xj0hK3dsnw=="
                , "json", "UTF-8"
                , "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs17iJUhoumOXUxubFSPBO9U1aDeex695GMGAuzjrl+T4CORLE6GWR2Z73bVmPt7rIJB9FR8XpxwmKNduTt/ay0DXFQ9IYW1M0Zu2G/2losgXnL86oo5uh5GOPzYrTy+opso45qxhd0De9JUjpkzw62GtpC272d9IDaUVXuYOmZBKSl5mTI+w0k2lzUHvBJo6TZ/605rOvh+zE1u/y6PwpqWMj1himXcLxrE9m5N9jlFb09cqYB23OA8ZPUM4UDU93zTZguJT+G74EcLYaaLHbN9spC9/aQLztBUX4/HW6rUkDyTDO3DOzEDR8VethExVCnrjv+4s3OwO2y0dnxvrhwIDAQAB", "RSA2");

		/*AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
		request.setNotifyUrl("http://clientv2.uqbike.com/zhifubaoPay/alipayNotify.do");

		JSONObject bizContent = new JSONObject();
		bizContent.put("auth_no","2023091910002001960556976149");
		bizContent.put("out_request_no","outRequestNo123");
		bizContent.put("amount",0.01);
		bizContent.put("remark","解冻资金");

		JSONObject extraParam = new JSONObject();
		JSONObject unfreezeBizInfo = new JSONObject();
		unfreezeBizInfo.put("bizComplete",true);
		extraParam.put("unfreezeBizInfo",unfreezeBizInfo);
		bizContent.put("extra_param",extraParam);

// 设置整体请求参数
		request.setBizContent(bizContent.toString());

// 使用execute方法发起请求
		AlipayFundAuthOrderUnfreezeResponse response = null;
		try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		if(response.isSuccess()){
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}*/

		/*AlipayTradePayRequest request = new AlipayTradePayRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("out_trade_no", "refund"+System.currentTimeMillis());
		bizContent.put("total_amount", 0.01);
		bizContent.put("subject", "骑行费用");
		bizContent.put("product_code", "PRE_AUTH_ONLINE");
		bizContent.put("auth_no", "2023092010002001960557383421");
		bizContent.put("auth_confirm_mode", "COMPLETE");
		bizContent.put("enable_pay_channels", "balance");
		bizContent.put("buyer_id", "2088222046970963");

		request.setBizContent(bizContent.toString());
		AlipayTradePayResponse response = null;
		try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		if(response.isSuccess()){
			System.out.println(response.getTradeNo());
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}*/


		/*AlipayTradeCloseRequest closeRequest = new AlipayTradeCloseRequest();
		JSONObject closebizContent = new JSONObject();
		closebizContent.put("trade_no", "2023092022001470961405388507");
		closeRequest.setBizContent(closebizContent.toString());
		AlipayTradeCloseResponse closeResponse = null;
		try {
			closeResponse = alipayClient.execute(closeRequest);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		if(closeResponse.isSuccess()){
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}*/

		/*AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
		JSONObject bizContent = new JSONObject();
		bizContent.put("trade_no", "2023092610002001960560352426");
		bizContent.put("refund_amount", 0.01);
		bizContent.put("out_request_no", "refund"+System.currentTimeMillis());
		request.setNotifyUrl("http://clientv2.uqbike.com/zhifubaoPay/alipayNotify.do");
		//// 返回参数选项，按需传入
		//JSONArray queryOptions = new JSONArray();
		//queryOptions.add("refund_detail_item_list");
		//bizContent.put("query_options", queryOptions);

		request.setBizContent(bizContent.toString());
		AlipayTradeRefundResponse response = null;
		try {
			response = alipayClient.execute(request);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		if(response.isSuccess()){
			System.out.println("调用成功");
		} else {
			System.out.println("调用失败");
		}*/

        AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
// 设置异步通知
        request.setNotifyUrl("http://clientv2.uqbike.com/zhifubaoPay/alipayNotify.do");
        JSONObject bizContent = new JSONObject();

        bizContent.put("auth_no", "2023092510002001950584852861");
        bizContent.put("out_request_no", "refund" + System.currentTimeMillis());
        bizContent.put("amount", 0.01);
        bizContent.put("remark", "退款");

        JSONObject extraParam = new JSONObject();
        JSONObject unfreezeBizInfo = new JSONObject();
        unfreezeBizInfo.put("bizComplete", true);
        extraParam.put("unfreezeBizInfo", unfreezeBizInfo);
        bizContent.put("extra_param", extraParam);

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用execute方法发起请求
        AlipayFundAuthOrderUnfreezeResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error("信用免押解冻异常", e);

        }

        if (response.isSuccess()) {
            System.out.println(1);
        }

    }

    @Override
    public String getOrder(Integer accountId, Integer userId, Double money, String remark, Boolean deposit, Integer adAccountId, Integer rechargeType) {
        /**订单编号*/
        //String orderNO= WeixinPayUtil.getNonceStr(deposit);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_pay);
        if (deposit) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_deposit);
        }
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(accountId);
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_APP);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        Account account =cacheService.getAccount(accountId);
        /**基础校验*/
        money = weixinPayService.order_base(userId, money, remark, deposit, orderNO, adAccountId,
                RechargeConstant.RECHARGE_ZFB_APP, rechargeType);
        Map<String, String> params = OrderInfoUtil2_0
                .buildOrderParamMap(zfbPayConfig.getPartner(), true, orderNO, money, zfbPayConfig.getNotiry_url(),account.getName()+"-"+remark);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String sign = OrderInfoUtil2_0.getSign(params, zfbPayConfig.getPrivate_key(), true);
        String orderInfo = orderParam + "&" + sign;
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE, null);
        return orderInfo;
    }

    @Override
    public Boolean zmxyCheck(Integer accountId, Integer userId) {
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_APP);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝接入信息未配置");
        }

        User user = userService.getByUserId(userId);
        if (!user.getNameAuth()) {
            throw new BaseException("-3024", "请先实名认证");
        }

        Boolean isSupport = ZMXYClient.isSupport(zfbPayConfig, user.getIdNO(), user.getName(), 650);

        if (!isSupport) {
            throw new BaseException("-3035", "芝麻信用分不足650");
        }

        /**更新数据库*/
        if (user.getDepositState() != DepositStateConstant.DEPOSIT_STATE_NOTPAY) {
            throw new BaseException("-3032", "押金状态非法");
        }

        /**更新押金状态*/
        userService.updateDeposit(userId, DepositStateConstant.DEPOSIT_STATE_ZMXY);

        return isSupport;
    }

    @Override
    public String createOrder_meal(User user, Integer mealId, Integer adAccountId) {
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        String orderInfo = getAppResult(RechargeConstant.recharge_meal, user, adAccountId, mealId);
        return orderInfo;
    }

    @Override
    public AlipayTradeCreateResponse createOrder_meal_xcx(User user, String code, Integer mealId,
                                                          Integer adAccountId) {
        /**订单编号*/
        //	String orderNO = "GXBIKEMEAL"+ DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_meal);
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        Account account = cacheService.getAccount(user.getAccountId());
        Account adAccount = cacheService.getAccount(adAccountId);
        Double money = weixinPayService.getMeal_base(RechargeConstant.RECHARGE_ZFB_XCX, user, mealId, orderNO, adAccountId);
        AlipayTradeCreateResponse alipayTradeCreateResponse = basePay(user.getAccountId(), code, user.getUserId(), zfbPayConfig, money, account.getName() + "-" + adAccount.getName() + "-" + GoodsConstant.GOODS_NAME_MEAL, orderNO, account.getName());
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return alipayTradeCreateResponse;
    }

    @Override
    public String fundAuthOrderAppFreeze(Integer accountId, Integer userId, Double money,
                                         String remark, Integer adAccountId, Integer rechargeType) {
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId,
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        String button = cacheService.getBrandRemoteConfigValue(accountId, BrandConstant.ZFB_FREEZE_BUTTON);
        if (button == null || "0".equalsIgnoreCase(button)) {
            throw new BaseException("-2016", "未开启信用免押功能");
        }
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_exempt);
        /*支付宝信用授权配置*/
        JSONObject jsonObject = cacheService.getBrandJsonConfig(accountId, BrandConstant.ZFB_FREEZE_CONFIG);
        String category = jsonObject.getString("category");
        String serviceId = jsonObject.getString("serviceId");
        /*基础校验*/
        money = weixinPayService.order_base(userId, money, remark, true, orderNO, adAccountId,
                RechargeConstant.RECHARGE_ZFB_XCX, rechargeType);
        String response = zfbFundAuthOrderAppFreeze(accountId, zfbPayConfig, orderNO, remark, money
                , category, serviceId);
        return response;
    }

    @Override
    public Boolean zfbFundAuthOrderAppUnfreeze(User user) {
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        Recharge recharge = rechargeService.getExemptByType(user.getUserId(), RechargeConstant.recharge_exempt);
        if (recharge == null) {
            throw new BaseException("-3068", "订单金额超出可退款金额，退款失败");
        }
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_exempt);
        Boolean result = zfbFundAuthOrderAppUnfreeze(user.getAccountId(), zfbPayConfig, orderNO, "押金退还", recharge.getMoney() / 100, recharge.getRemark());
        return result;
    }

    @Override
    public void getAlipayUserInfo(String accessToken, User user, ZfbPayConfig zfbPayConfig) {
        BrandRemoteConfig brandRemoteConfig = cacheService.getBrandRemoteConfig(user.getAccountId(), BrandConstant.ZFB_AUTH_CONFIG);
        if (brandRemoteConfig == null || Integer.valueOf(brandRemoteConfig.getParamKV().substring(brandRemoteConfig.getParamKV().indexOf("=") + 1)) == 0) {
            return;
        }
        AlipayClient alipayClient = aliConfigService.getAliPayClient(user.getAccountId(), zfbPayConfig).getAlipayClient();
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response;
        try {
            response = alipayClient.execute(request, accessToken);
            if (response.isSuccess()) {
                userService.updateNameAuth(user.getUserId(), response.getCertNo(), response.getUserName());
                user.setIdNO(response.getCertNo());
                user.setName(response.getUserName());
                user.setNameAuth(true);
                /**兼容根据身份证设置性别生日*/
                userService.editSex(user.getUserId());
                /**兼容用户参与活动记录用户名称*/
                userRewardLogService.editName(response.getUserName(), user.getUserId());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

    }

    private String getAppResult(Integer from, User user, Integer adAccountId, Integer tmpId) {
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_APP);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        /**订单编号*/
        String orderNO = "";
        Double money = 0D;
        String remark="";
        Account account =cacheService.getAccount(user.getAccountId());
        if (RechargeConstant.recharge_Mem == (from)) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_Mem);
            User userDB = userService.getByUserId(user.getUserId());
            weixinPayService.checkIsByMem(userDB, adAccountId);
            money = weixinPayService.getMemberOrder_base(RechargeConstant.RECHARGE_ZFB_APP, user, adAccountId, orderNO, tmpId);
            remark=account.getName()+"-"+GoodsConstant.GOODS_NAME_MEMBERORDER;
        } else if (RechargeConstant.recharge_meal == (from)) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_meal);
            money = weixinPayService.getMeal_base(RechargeConstant.RECHARGE_ZFB_APP, user, tmpId, orderNO, adAccountId);
            remark=account.getName()+"-"+GoodsConstant.GOODS_NAME_MEAL;
        } else if (RechargeConstant.recharge_rideCard == (from)) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_rideCard);
            money = weixinPayService.getRideCardOrder_base(RechargeConstant.RECHARGE_ZFB_APP, user, tmpId, orderNO, adAccountId);
            remark=account.getName()+"-"+GoodsConstant.GOODS_NAME_RIDECARDORDER;
        } else if (RechargeConstant.recharge_vip == (from)) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_vip);
            money = weixinPayService.getVipOrder_base(RechargeConstant.RECHARGE_ZFB_APP, user, tmpId, orderNO, adAccountId);
            remark=account.getName()+"-"+GoodsConstant.GOODS_NAME_VIPORDER;
        }
        Map<String, String> params = OrderInfoUtil2_0
                .buildOrderParamMap(zfbPayConfig.getPartner(), true, orderNO, money, zfbPayConfig.getNotiry_url(),remark);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String sign = OrderInfoUtil2_0.getSign(params, zfbPayConfig.getPrivate_key(), true);
        String orderInfo = orderParam + "&" + sign;
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return orderInfo;
    }

    @Override
    public String createOrder_memberFee(User user, Integer memberFeeId, Integer adAccountId) {
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        String orderInfo = getAppResult(RechargeConstant.recharge_Mem, user, adAccountId, memberFeeId);
        return orderInfo;
    }

    @Override
    public String createOrder_rideCard(User user, Integer rideCardId, Integer adAccountId) {
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        String orderInfo = getAppResult(RechargeConstant.recharge_rideCard, user, adAccountId, rideCardId);

        return orderInfo;
    }

    @Override
    public String createOrder_vip(User user, Integer vipId, Integer adAccountId) {
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        String orderInfo = getAppResult(RechargeConstant.recharge_vip, user, adAccountId, vipId);
        return orderInfo;
    }

    @Override
    public AlipayTradeCreateResponse getOrder_xcx(Integer accountId, String code, Integer userId, Double money,
                                                  String remark, Boolean deposit, Integer adAccountId, Integer rechargeType) {
        /**订单编号*/
        //String orderNO= WeixinPayUtil.getNonceStr(deposit);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_pay);
        if (deposit) {
            orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_deposit);
        }
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(accountId);
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(accountId, RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        User user = userService.getByUserId(userId);
        Account account = cacheService.getAccount(accountId);
        //充值结束订单区域为订单区域
        if (Objects.equals(rechargeType, RechargeConstant.recharge_returnBike)) {
            Machine machine = machineBorrowDao.getRideByUserId(user.getUserId());
            if (machine != null) {
                adAccountId = machine.getAccountId();
            }
        }
        /**基础校验*/
        money = weixinPayService.order_base(userId, money, remark, deposit, orderNO, adAccountId,
                RechargeConstant.RECHARGE_ZFB_XCX, rechargeType);
        String goodRemark = GoodsConstant.GOODS_NAME_ORDER;
        if (user.getRideMoney() > 0) {
            //有欠款，补交区域为骑行订单所在区域
            String accountIdStr = redisService.get(RedisConstant.QKBJ_ACCOUNTID + userId);
            if (accountIdStr != null) {
                adAccountId = Integer.parseInt(accountIdStr);
            }
            goodRemark = GoodsConstant.GOODS_NAME_QKBJ;
        }
        Account adAccount = cacheService.getAccount(adAccountId);
        AlipayTradeCreateResponse alipayTradeCreateResponse = basePay(user.getAccountId(), code, user.getUserId(), zfbPayConfig, money, account.getName()+ "-" + adAccount.getName() + "-" + goodRemark, orderNO, account.getName());
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return alipayTradeCreateResponse;
    }

    @Override
    public AlipayTradeCreateResponse createOrder_memberFee_xcx(User user, String code, Integer memberFeeId,
                                                               Integer adAccountId) {
        /**订单编号*/
        //String orderNO = "GXBIKEDM"+ DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_Mem);
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        User userDB = userService.getByUserId(user.getUserId());
        Account account = cacheService.getAccount(user.getAccountId());
        weixinPayService.checkIsByMem(user, adAccountId);
        Double money = weixinPayService.getMemberOrder_base(RechargeConstant.RECHARGE_ZFB_XCX, user, adAccountId, orderNO, memberFeeId);
        Account adAccount = cacheService.getAccount(adAccountId);
        AlipayTradeCreateResponse alipayTradeCreateResponse = basePay(userDB.getAccountId(), code, user.getUserId(), zfbPayConfig, money, account.getName() + "-" + adAccount.getName() + "-" + GoodsConstant.GOODS_NAME_MEMBERORDER, orderNO, account.getName());
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return alipayTradeCreateResponse;
    }

    @Override
    public AlipayTradeCreateResponse createOrder_rideCard_xcx(User user, String code, Integer rideCardId,
                                                              Integer adAccountId) {
        /**订单编号*/
        //String orderNO = "GXBIKERC"+ DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_rideCard);
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        Account account = cacheService.getAccount(user.getAccountId());
        //Double money = getRideCardOrder_base(RechargeConstant.RECHARGE_ZFB_XCX,user.getUserId(),rideCardId,orderNO);
        Double money = weixinPayService.getRideCardOrder_base(RechargeConstant.RECHARGE_ZFB_XCX, user, rideCardId, orderNO, adAccountId);
        Account adAccount = cacheService.getAccount(adAccountId);
        AlipayTradeCreateResponse alipayTradeCreateResponse = basePay(user.getAccountId(), code, user.getUserId(), zfbPayConfig, money, account.getName() + "-" + adAccount.getName() + "-" + GoodsConstant.GOODS_NAME_RIDECARDORDER, orderNO, account.getName());
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return alipayTradeCreateResponse;
    }

    @Override
    public AlipayTradeCreateResponse createOrder_vip_xcx(User user, String code, Integer vipId, Integer adAccountId) {
        /**订单编号*/
        //	String orderNO = "GXBIKEVIP"+ DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil.buildRandom(6);
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_vip);
        /**聚合支付校验*/
        adaPayService.checkIsAdaPay(user.getAccountId());
        /**支付配置信息*/
        ZfbPayConfig zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(),
                RechargeConstant.ZFB_PAY_XCX);
        if (zfbPayConfig == null) {
            throw new BaseException("-2009", "该品牌支付宝未配置");
        }
        Account account = cacheService.getAccount(user.getAccountId());
        Integer userId = user.getUserId();
        //Double money = getVipOrder_base(RechargeConstant.RECHARGE_ZFB_XCX,userId,vipId,orderNO,adAccountId);
        Double money = weixinPayService.getVipOrder_base(RechargeConstant.RECHARGE_ZFB_XCX, user, vipId, orderNO, adAccountId);
        Account adAccount = cacheService.getAccount(adAccountId);
        AlipayTradeCreateResponse alipayTradeCreateResponse = basePay(user.getAccountId(), code, user.getUserId(), zfbPayConfig, money, account.getName() + "-" + adAccount.getName() + "-" + GoodsConstant.GOODS_NAME_VIPORDER, orderNO, account.getName());
        /**支付信息推送mq队列*/
        weixinPayService.sendPayMsg(orderNO, RechargeConstant.PAY_CREATE,null);
        return alipayTradeCreateResponse;
    }

    /**
     * 支付宝小程序创建订单
     *
     * @param accountId    品牌id
     * @param code         code
     * @param userId       用户id
     * @param zfbPayConfig 支付宝配置
     * @param totalMoney   充值金额
     * @param title        标题
     * @param orderNO      订单号
     * @return
     */
    public AlipayTradeCreateResponse basePay(Integer accountId, String code, Integer userId,
                                             ZfbPayConfig zfbPayConfig, Double totalMoney, String title, String orderNO, String brandName) {
        //获取到阿里客户端
        AliConfigWrap alipayClient = aliConfigService.getAliPayClient(accountId, zfbPayConfig);

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.create.
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        //订单号
        String out_trade_no = orderNO;
        //金额 单位元
        String total_amount = String.valueOf(totalMoney);
        //订单标题
        String subject = title;
        String aliUserId = SystemData.aliPayMap.get(userId);
        if (aliUserId == null) {
            AlipaySystemOauthTokenResponse reponse = aliConfigService.alipaySystemOauthToken(accountId, code, zfbPayConfig);
            aliUserId = reponse.getUserId();
        }
        /**记录用户第三方唯一id*/
        UserOtherBound userOtherBound = new UserOtherBound(userId, aliUserId, accountId, RechargeConstant.WXZFF_AUTH, UserConstant.OTHER_TYPE_ZFB);
        userOtherBoundService.insert(userOtherBound);
            request.setNotifyUrl(zfbPayConfig.getNotiry_url());


        AlipayTradeCreateModel model = new AlipayTradeCreateModel();
        model.setOutTradeNo(out_trade_no);
        model.setTotalAmount(total_amount);
        model.setSubject(subject);
        model.setProductCode("JSAPI_PAY");
        model.setOpAppId(zfbPayConfig.getPartner());
        model.setBuyerId(aliUserId);
        model.setTimeExpire(DateTimeUtil.getOneMinuteTime());
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088801091822274");
        model.setExtendParams(extendParams);
        request.setBizModel(model);
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
//        request.setBizContent("{" +
//                "\"out_trade_no\":\"" + out_trade_no + "\"," +
//                "\"total_amount\":" + total_amount + "," +
//                "\"subject\":\"" + subject + "\"," +
//                "\"product_code\":\"JSAPI_PAY\"," +
//                "\"op_app_id\":\"" + zfbPayConfig.getPartner() + "\"," +
//                "\"buyer_id\":\"" + aliUserId + // 小程序支付场景中该参数必传
//                "\",\"time_expire\":\"" + DateTimeUtil.getOneMinuteTime() + "\"}");
        log.info("支付宝创建订单请求参数：{},{}" ,out_trade_no,"2088801091822274");
        AlipayTradeCreateResponse response = new AlipayTradeCreateResponse();

        try {
            response = alipayClient.getAlipayClient().execute(request);
            //LogUtil.info(response.getMsg()+"----------"+response.getCode()+","+response.getSubCode()+","+response.getSubMsg());
            String outTradeNo = response.getOutTradeNo();//商户订单号
            String trade_no = response.getTradeNo();// 获取返回的tradeNO。
            log.info("商户订单号： " + outTradeNo);
            log.info("支付宝交易号: " + trade_no);
            // 支付宝判断订单创建是否成功是否可以依靠这个
            if (!response.isSuccess()) {
                String externalExceptionMsg = response.getSubMsg();
                throw new ExternalException("创建订单失败：商户异常",externalExceptionMsg,brandName);
            }
        } catch (AlipayApiException e) {
            log.error("支付宝创建订单异常",e);
            throw new ExternalException("创建订单失败：商户异常",e.getErrMsg(), brandName);
        }
        return response;
    }

    /**
     * 支付宝预授权支付
     *
     * @param accountId
     * @param zfbPayConfig
     * @param orderNO
     * @param title
     * @param money
     * @return
     */
    private String zfbFundAuthOrderAppFreeze(Integer accountId, ZfbPayConfig zfbPayConfig
            , String orderNO, String title, Double money, String category, String serviceId) {
        AlipayClient alipayClient = aliConfigService.getAliPayClient(accountId, zfbPayConfig).getAlipayClient();

        AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
        // 设置异步通知
        request.setNotifyUrl(zfbPayConfig.getNotiry_url());

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_order_no", orderNO);
        bizContent.put("out_request_no", orderNO);
        bizContent.put("order_title", title);
        bizContent.put("amount", money);
        bizContent.put("product_code", "PRE_AUTH_ONLINE");
        //bizContent.put("payee_user_id","2088102000275795");
        bizContent.put("timeout_express", "5m");

        bizContent.put("deposit_product_mode", "DEPOSIT_ONLY");

        //// 设置扩展参数
        JSONObject extraParam = new JSONObject();
        extraParam.put("category", category);
        extraParam.put("serviceId", serviceId);
        //extraParam.put("creditExtInfo","2020042800000000000001450466");
        bizContent.put("extra_param", extraParam);

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用sdkExecute方法发起请求
        AlipayFundAuthOrderAppFreezeResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }

        if (response.isSuccess()) {
            return response.getBody();
        } else {
            return null;
        }
    }

    /**
     * 信用免押解冻
     *
     * @param accountId
     * @param zfbPayConfig
     * @param orderNO
     * @param remark
     * @param money
     * @param auth_no
     * @return
     */
    private boolean zfbFundAuthOrderAppUnfreeze(Integer accountId, ZfbPayConfig zfbPayConfig
            , String orderNO, String remark, Double money, String auth_no) {

        AlipayClient alipayClient = aliConfigService.getAliPayClient(accountId, zfbPayConfig).getAlipayClient();
        AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
// 设置异步通知
        request.setNotifyUrl(zfbPayConfig.getNotiry_url());
        JSONObject bizContent = new JSONObject();

        bizContent.put("auth_no", auth_no);
        bizContent.put("out_request_no", orderNO);
        bizContent.put("amount", money);
        bizContent.put("remark", remark);

        JSONObject extraParam = new JSONObject();
        JSONObject unfreezeBizInfo = new JSONObject();
        unfreezeBizInfo.put("bizComplete", true);
        extraParam.put("unfreezeBizInfo", unfreezeBizInfo);
        bizContent.put("extra_param", extraParam);

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用execute方法发起请求
        AlipayFundAuthOrderUnfreezeResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            log.error("信用免押解冻异常", e);
            return false;
        }

        if (response.isSuccess()) {
            return true;
        }
        return false;
    }

    /**
     * 支付宝信用分扣费
     *
     * @param accountId
     * @param zfbPayConfig
     * @param orderNO
     * @param remark
     * @param money
     * @param auth_no
     * @param buyer_id
     */
    public boolean cashFee(Integer accountId, ZfbPayConfig zfbPayConfig
            , String orderNO, String remark, Double money, String auth_no, String buyer_id) {
        AlipayClient alipayClient = aliConfigService.getAliPayClient(accountId, zfbPayConfig).getAlipayClient();
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        request.setNotifyUrl(zfbPayConfig.getNotiry_url());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNO);
        bizContent.put("total_amount", money);
        bizContent.put("subject", remark);
        bizContent.put("product_code", "PRE_AUTH_ONLINE");
        bizContent.put("auth_no", auth_no);
        bizContent.put("auth_confirm_mode", "COMPLETE");
        bizContent.put("buyer_id", buyer_id);

        request.setBizContent(bizContent.toString());
        AlipayTradePayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
        if (response.isSuccess()) {
            return true;
        }
        return false;
    }

}  